import { createRouter, createWebHistory, onBeforeRouteLeave } from "vue-router";

import TemplateDetail from "@/views/TemplateDetail.vue";
import Home from "@/views/Home.vue";
import store from "@/store";
import axios from "axios";
import { message } from "ant-design-vue";

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/",
      name: "home",
      component: ()=>import('@/views/Home.vue'),
      meta: { withHeader: true, disableLoading: false, title: "欢迎" }
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/Login.vue"),
      meta: { disableLoading: true, redirectAlreadyLogin: true, title: "登录" },
    },
    {
      path: "/editor/:id",
      name: "editor",
      component: () => import(/* webpackChunkName: "editor" */ '@/views/Editor.vue'),
      meta: { requiredLogin: true, title: "编辑" },
    },
    {
      path: "/template/:id",
      name: "template",
      component: () => import('@/views/TemplateDetail.vue'),
      meta: { withHeader: true, title: "模板详情" },
    },
  ],
});

router.beforeEach(async (to, from) => {
  const { user } = store.state;
  const { token, isLogin } = user;
  const { redirectAlreadyLogin, requiredLogin, title } = to.meta;
  if (title) {
    document.title = title as string;
  }
  if (!isLogin) {
    if (token) {
      axios.defaults.headers.common.Authorization = `Bearer ${token}`;
      try {
        await store.dispatch("fetchCurrentUser");
        if (redirectAlreadyLogin) {
          return "/";
        }
      } catch (e) {
        message.error("登录信息过期，请重新登录", 2);
        store.commit("logout");
        return "/login";
      }
    } else {
      if (requiredLogin) {
        return "/login";
      }
    }
  } else {
    // 如果已经登录，但是去登录页，则跳转到首页
    if (redirectAlreadyLogin) {
      return "/";
    }
  }
});

export default router;
